package com.example.demo.evaluation;

import com.example.demo.Redis.RedisUtil;
import com.example.demo.common.RedisConstants;
import com.example.demo.pojo.Identity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class EvaluationEngine {

    @Resource
    private RedisUtil redisUtil;

    public void evaluate(Identity identity,String reqResult){
        String user = identity.getIdentity_user().getUser();
        String mac = identity.getIdentity_device().getDevice_Mac();
        String ip = identity.getIdentity_env().getIp();
        String os = identity.getIdentity_env().getOS();
        String version = identity.getIdentity_env().getVersion();

        switch(reqResult){
            case "success":
                evaluate(user,mac,ip,os,version,1);
                break;

            case "trust not enough":
                evaluate(user,mac,ip,os,version,-1);
                break;

            case "permission denied":
                evaluate(user,mac,ip,os,version,-2);
                break;
        }

    }

    private void reset(String user, String mac, String ip, String os, String version, int change) {
        redisReset(RedisConstants.user_prefix+user,change);
        redisReset(RedisConstants.mac_prefix+mac,change);
        redisReset(RedisConstants.ip_prefix+ip,change);
        redisReset(RedisConstants.os_prefix+os,change);
//        redisReset(RedisConstants.version_prefix+version,change);
    }

    private void evaluate(String user, String mac, String ip, String os, String version, int change){
        reset(user, mac, ip, os, version, change);
    }

    private void redisReset(String key, int change){
        String trust = String.valueOf(redisUtil.get(key));
        if(trust.equals("null")){
            redisUtil.set(key,change);
            return;
        }
        int t = Integer.parseInt(trust);


        redisUtil.set(key,t+change);
    }

}
